<script setup lang="ts">
import { ref } from "vue";
import {
  ElMessage,
  genFileId,
  UploadInstance,
  UploadProps,
  UploadRawFile,
  UploadUserFile,
} from "element-plus";
import { getAllGradeAPI } from "../../api/user.ts";
import { addAssignmentURL } from "../../api/assignment.ts";

const upload = ref<UploadInstance>();

const title = ref<string>("");

const emits = defineEmits(["upload-already"]);

const handleExceed: UploadProps["onExceed"] = (files) => {
  upload.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  upload.value!.handleStart(file);
  return;
};

const handleUploadSuccess = (response: any) => {
  if (response.data) {
    ElMessage({
      message: "上传作业成功",
      type: "success",
    });
    fileList.value.pop();
    emits("upload-already");
  } else {
    ElMessage.error(`上传失败: ${response.message}`);
  }
};

const beforeUploadFile = () => {
  if (title.value !== "" && fileList.value.length > 0) {
    upload.value?.submit();
    // console.log(upload.value);
  } else {
    ElMessage.error("上传失败");
  }
};
const grades = ref<{ id: number; title: string }[]>([]);

getAllGradeAPI()
  .then((response) => {
    if (response.status !== 200) {
      throw new Error("网络错误");
    }
    return response.data;
  })
  .then((result) => {
    grades.value = result.data;
  });

const grade = ref<{ id: number; title: string }>();
const date = ref();
const fileList = ref<UploadUserFile[]>([]);
</script>

<template>
  <el-form :label-position="'top'">
    <el-form-item label="作业标题: ">
      <el-input type="text" v-model="title" />
    </el-form-item>
    <el-form-item>
      <el-select v-model="grade">
        <el-option
          v-for="item in grades"
          :key="item.id"
          :label="item.title"
          :value="item.id"
        />
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-date-picker
        v-model="date"
        type="datetime"
        placeholder="请选择截止时间"
      />
    </el-form-item>
    <el-form-item>
      <el-upload
        :data="{
          title,
          grade,
          date,
        }"
        v-model:file-list="fileList"
        :action="addAssignmentURL"
        :auto-upload="false"
        :limit="1"
        name="content"
        ref="upload"
        :on-exceed="handleExceed"
        :on-success="handleUploadSuccess"
      >
        <template #trigger>
          <el-button type="primary">选择文件</el-button>
        </template>
        <template #tip> <div>请上传一个作业文件</div> </template>
      </el-upload>
    </el-form-item>
    <el-button type="success" @click="beforeUploadFile">点击上传</el-button>
  </el-form>
</template>

<style scoped></style>
